#include "OggFile.h"
#include "stb_vorbis.c"

using namespace fxcc;

OggFile::OggFile(const std::string& path)
	:m_Path(path)
{
	Load();
}

OggFile::~OggFile()
{
}

bool OggFile::Load()

{
    int error = 0;
    stb_vorbis* vorbis = stb_vorbis_open_filename(m_Path.c_str(), &error, nullptr);
    if (!vorbis)
    {
//        ztclog::info("Failed to open Ogg file: %s", m_Path.c_str());
        return false;
    }

    stb_vorbis_info info = stb_vorbis_get_info(vorbis);
    m_Channels = info.channels;
    m_SampleRate = info.sample_rate;

    m_SampleCount = stb_vorbis_stream_length_in_samples(vorbis);

    m_PCMData.resize(m_SampleCount * m_Channels);
    int samples_read = stb_vorbis_get_samples_short_interleaved(vorbis, m_Channels, m_PCMData.data(), m_SampleCount * m_Channels);

    if (samples_read > 0)
    {
        m_Available = true;
    }
    else
    {
//        ztclog::info("Failed to decode Ogg file: %s\n", m_Path.c_str());
        m_PCMData.clear();
    }

    stb_vorbis_close(vorbis);
    return m_Available;
}

int OggFile::GetAlFormat()
{

    ALenum format;

    if (m_Channels == 1)
    {
        format = AL_FORMAT_MONO16;
    }
    else if (m_Channels== 2)
    {
        format = AL_FORMAT_STEREO16;
    }
    else
    {
        format = 0; 
    }
    return format;

}

size_t OggFile::DataSize()
{
    return m_Available ? m_PCMData.size() * sizeof(int16_t) : 0;
}

int OggFile::SampleRate()
{
    return m_SampleRate;
}


int OggFile::Channels()

{
    return m_Channels;
}